package com.example.quartz.utils;

import lombok.extern.slf4j.Slf4j;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import static com.example.quartz.constant.JavaFileConstant.*;

/**
 * @description:
 * @author: wlp
 * @createDate: 2020-01-06
 * @version: 1.0
 */
@Slf4j
public class DynamicCompilerJavaUtil {

    private synchronized static void compile(String javaSourceCode, String className) throws Exception {
        File file = new File(BASE_DIR + className + JAVA_SUFFIX);
        boolean newFile = file.createNewFile();
        if (newFile) {
            file.deleteOnExit();
            // 将代码输出到文件
            PrintWriter out = new PrintWriter(new FileOutputStream(file));
            out.println(javaSourceCode);
            out.close();
            //动态编译
            JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
            int status = javac.run(null, null, null, "-d", BASE_DIR, BASE_DIR + file.getName());
            if (status != 0) {
                throw new Exception("语法错误！");
            }
        } else {
            throw new Exception("创建文件失败！");
        }
    }

    public static synchronized void run(String javaSourceCode, String methodName, String className, Object... params) throws Exception {
        compile(javaSourceCode, className);
        new File(BASE_DIR + className + SUFFIX).deleteOnExit();
        try {
            MyClassLoader loader = new MyClassLoader();
            Class cls = loader.findClass(className);
            if (null != params) {
                Method main = cls.getMethod(methodName, params.getClass().getComponentType());
                main.invoke(cls, params);
            } else {
                Method main = cls.getMethod(methodName, null);
                main.invoke(cls, null);
            }
        } catch (Exception se) {
            se.printStackTrace();
            log.error("编译运行失败==》", se);
        }
    }

    public static void main(String[] args) {
        String str = "import com.baomidou.mybatisplus.core.toolkit.IdWorker;" +
                "public class TestJava{\n" +
                " public static void method(Object name){\n" +
                "         for (int i = 0; i < 10; i++) {\n" +
                "            String uuid = IdWorker.get32UUID();\n" +
                "            System.out.println(uuid);\n" +
                "            System.out.println(name);\n" +
                "        }\n" +
                "\n" +
                " }\n" +
                "}";
        try {
            run(str, "method", "TestJava", "大吉大利");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("代码编译运行出错");
        }
    }
}
